package com.ming.interceptor;

import com.ming.util.TraceIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * TraceId拦截器
 * 为每个请求生成和管理TraceId
 *
 * @author ming
 * @version 1.0
 */
@Slf4j
@Component
public class TraceIdInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID_HEADER = "X-Trace-Id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 尝试从请求头获取TraceId
        String traceId = request.getHeader(TRACE_ID_HEADER);

        // 如果没有TraceId，则生成一个新的
        if (traceId == null || traceId.isEmpty()) {
            traceId = TraceIdUtils.generateTraceId();
        }

        // 设置TraceId到MDC
        TraceIdUtils.setTraceId(traceId);

        // 设置TraceId到响应头
        response.setHeader(TRACE_ID_HEADER, traceId);

        log.debug("设置TraceId: {}, URI: {}", traceId, request.getRequestURI());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理TraceId
        TraceIdUtils.clearTraceId();
        log.debug("清理TraceId: {}, URI: {}", TraceIdUtils.getTraceId(), request.getRequestURI());
    }
}